import { intersection } from 'lodash-es';

import { useAuthStore } from '@/store/modules/auth';
import { isArray } from '@/utils/is';

/** 授权函数 */
export function useAuth() {
  const authStore = useAuthStore();

  /** 是否拥有授权 */
  function hasAuth(value?: string | string[], type = authStore.getAuthType, def = true): boolean {
    // 默认拥有
    if (!value) {
      return def;
    } else if (isArray(value) && !(value?.length > 0)) {
      return def;
    }

    const codes = type === 'code' ? authStore.getAccessCodes : authStore.getRoleCodes;
    if (!isArray(value)) {
      const splits = ['||', '&&'];
      const splitName = splits.find((item) => value.includes(item));
      if (splitName) {
        const splitCodes = value.split(splitName);
        return splitName === splits[0]
          ? intersection(splitCodes, codes).length > 0
          : intersection(splitCodes, codes).length === splitCodes.length;
      }
      return codes.includes(value);
    }
    return intersection(value, codes).length > 0;
  }

  return {
    /** 是否拥有授权 */
    hasAuth,
    /** 授权类型 */
    authType: authStore.getAuthType,
  };
}
